﻿module Sustainalytics.Screening {

    import Common = Sustainalytics.Common;

    export class FilterService implements IFilterService {

        constructor(
            private $q: ng.IQService,
            private $http: ng.IHttpService,
            private $location: ng.ILocationService,
            private notificationFactory: Common.INotificationFactory,
            private staticObjects: Common.IStaticObjects,
            private $rootScope: ng.IScope)
        {
            var ctx = this;
        }

        // show error message for a given error code
        private showError(err) {
            var ctx = this;
            if (err && err['errorCode'])
                ctx.notificationFactory.error('', ctx.staticObjects.getErrorMesageByStatusCode(err['errorCode'], err['errorCode']));
        }

        private showMessage(msg) {
            var ctx = this;
            ctx.notificationFactory.success(msg);
        }

        //screeningtoolserv/api/v1/filters/{id?}
        private filtersUrl(id?: string): string {
            return this.$location.protocol() + "://" + this.$location.host() + ":" + this.$location.port()
                + this.staticObjects.screeningToolServBaseUrl + "/filters/" + ((id) ? id : "");
        }

        private accountFiltersUrl(accountId: string): string {
            return this.$location.protocol() + "://" + this.$location.host() + ":" + this.$location.port()
                + this.staticObjects.screeningToolServBaseUrl + "/filters/adminfilters/" + accountId;
        }


        public getAccountFilters(accountId: string): ng.IPromise<FilterDto[]>
        {
            var ctx = this;
            var def = ctx.$q.defer();
            var promise = ctx.$http.get(ctx.accountFiltersUrl(accountId));

            promise
                .success(function (data) {
                def.resolve(data);
            })
                .error(function (data, status, headers, config) {
                def.reject({ data: data, status: status, headers: headers, config: config });
            });

            return def.promise;
        }

        public getUserFilters(targetType: TargetType): ng.IPromise<FilterDto[]>
        {
            var ctx = this;
            var def = ctx.$q.defer();
            var promise = ctx.$http.get(ctx.filtersUrl(), { params: { withExtendedData: true, target: targetType } });

            promise
                .success(function (data) {
                def.resolve(data);
            })
                .error(function (data, status, headers, config) {
                def.reject({ data: data, status: status, headers: headers, config: config });
            });

            return def.promise;
        }

        public getFullFilterById(filterId: string, accountId: string, userId: string): ng.IPromise<FilterDto> {
            var ctx = this;
            var def = this.$q.defer();

            var query =
                {
                    accountId: accountId,
                    userId: userId,
                    includeAllDetails: true
                };

            var url = ctx.filtersUrl(filterId) + "?" + $.param(query);
            var promise = this.$http.get(url);

            promise
                .success(function (data) {
                def.resolve(data);
            })
                .error(function (data, status, headers, config) {
                def.reject({ data: data, status: status, headers: headers, config: config });
            });

            return def.promise;
        }

        public saveFilter(filter: FilterDto): ng.IPromise<FilterDto>
        {    
            var ctx = this;    
            var def = this.$q.defer();

            var promise =  this.$http({
                method: "POST",
                url: this.filtersUrl(),
                data: filter
            });

            promise
                .success(function (data) {                
                def.resolve(data);
            })
                .error(function (data, status, headers, config) {
                def.reject({ data: data, status: status, headers: headers, config: config });
            });

            return def.promise;
        }

        public editFilter(filter: FilterDto): ng.IPromise<FilterDto> {
            var ctx = this;
            var def = this.$q.defer();

            var url: string = ctx.filtersUrl();

            var promise: ng.IHttpPromise<{}> = this.$http.put(url, filter);

            promise
                .success(function (data) {
                def.resolve(data);
            })
                .error(function (data, status, headers, config) {
                def.reject({ data: data, status: status, headers: headers, config: config });
            });

            return def.promise;
        }

        public deleteFullFilter(filterId: string): ng.IPromise<{}> {

            var ctx = this;
            var def = this.$q.defer();

            var url: string = ctx.filtersUrl(filterId);
            var promise: ng.IHttpPromise<{}> = this.$http.delete(url);

            promise
                .success(function (data) {
                ctx.showMessage("Filter deleted successfully!");
                def.resolve(data);
            })
                .error(function (data, status, headers, config) {
                def.reject({ data: data, status: status, headers: headers, config: config });
            });

            return def.promise;
        }

        
        public updateSelectedCriteriaOrderNumber(filterId: string, criteriaIds: Array<string>): ng.IPromise<{}> {
            var ctx = this;
            var def = this.$q.defer();

            var promise = this.$http({
                method: "PATCH",
                url: this.filtersUrl(),
                data: { resourceId: filterId, orderedCriteriaIds: criteriaIds }
            });

            promise
                .success(function (data) {
                def.resolve(data);
            })
                .error(function (data, status, headers, config) {
                def.reject({ data: data, status: status, headers: headers, config: config });
            });

            return def.promise;

        }

        public saveUserCustomFilterOrder(targetType: TargetType, screenRegion: ScreenRegion, filterIds: Array<string>): ng.IPromise<{}> {
            var ctx = this;
            var def = this.$q.defer();

            var promise = this.$http({
                method: "PATCH",
                url: this.filtersUrl() + '/customFilterOrder',
                data: { targetType: targetType, screenRegion: screenRegion, filterIds: filterIds }
            });

            promise
                .success(function (data) {
                def.resolve(data);
            })
                .error(function (data, status, headers, config) {
                def.reject({ data: data, status: status, headers: headers, config: config });
            });

            return def.promise;

        }
        
    }

    var mod = angular.module(screeningToolModuleName);

    mod.service('FilterService',
        ['$q', '$http', '$location', 'notificationFactory', 'staticObjects', '$rootScope', FilterService]);
}